<template>
  <div class="right-submit-area">
    <el-tree
      ref="tree"
      :data="treeData"
      class="scroll-area"
      :highlight-current="!canSet"
      :show-checkbox="canSet"
      :props="defaultProps"
      :default-expanded-keys="expandedKeys"
      node-key="authorityId"
      @node-click="handleNodeClick"
      :check-strictly='checkStrictly'
    >
    </el-tree>
    <div class="btn" v-if="canSet">
      <el-button style="width: 140px" type="primary" @click="submitAuth"
        >保存</el-button
      >
      <el-button style="width: 140px" @click="reset">重置</el-button>
    </div>
  </div>
</template>

<script>
import { arrayToTree } from '@/utils';
import { list } from '@/api/system/authority';

export default {
  name: 'AuthTree',
  props: {
    canSet: {
      type: Boolean,
      default: false,
    },
    checkStrictly: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      authData: [],
      defaultProps: {
        children: 'children',
        label: 'authorityName',
      },
      treeData: [],
      expandedKeys: [],
    };
  },
  created() {
    this.getAuthList();
  },
  computed: {},
  watch: {},
  methods: {
    setSelect(arr) {
      this.$refs.tree.setCheckedKeys(arr);
      this.expandedKeys = arr;
      //this.setExpand();
    },
    setExpand() {
      let treeNodes = this.$refs.tree.store._getAllNodes();
      for (let i = 0; i < treeNodes.length; i++) {
        if (treeNodes[i].level === 1) {
          treeNodes[i].expanded = true;
        } else {
          treeNodes[i].expanded = treeNodes[i].checked;
        }
      }
    },
    handleNodeClick(data, node) {
      this.$emit('auth-select', data);
    },
    submitAuth() {
      let arr = this.$refs.tree
        .getCheckedNodes()
        .map((item) => item.authorityId);
      //console.log(this.$refs.tree.getCheckedNodes(false, true));
      this.$emit('auth-submit', arr);
    },
    reset() {
      this.$emit('auth-reset');
    },
    getAuthList() {
      list().then((res) => {
        this.authData = res.rows;
        this.treeData = arrayToTree(res.rows, 'authorityId', 'parentId');

        /*let topLevelId = this.treeData.map(item => item.authorityId);
        this.$nextTick(res => {
          this.expandedKeys = topLevelId;
        })*/
      });
    },
  },
};
</script>

<style scoped lang="scss">
@import '~@/styles/mixin.scss';
.right-submit-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow-y: hidden;
  .scroll-area {
    flex: 1;
    @include noScrollBar();
  }
  .btn {
    margin-top: 10px;
    text-align: right;
  }
}
</style>
